// hooks/record.ts
import { useCallback,useState } from 'react';
import { getPrimaryFieldName } from '../utils';
import { getLocale } from '../components/locales';
export const useRecord = ( ) => {
  const locale = getLocale('zh-CN');
   
  const [records, setRecords] = useState<DocRecord[]>([]);
  // 加载记录列表
  const loadRecords = useCallback(async (sheetId?: string) => {
    try {
      const recordData = await Dingdocs.script.run('getRecords', sheetId);
      console.log('Loaded records:', recordData);
      setRecords(recordData.records); // 直接在 hook 内部更新状态
      return recordData.records;
    } catch (error: any) {
      console.error('Load records failed:', error);
      throw error;
    }
  }, []);

   const loadAllRecords=useCallback(async(sheetId?:string)=>{
    try {
      const allRecords = await Dingdocs.script.run('getAllRecords', sheetId);
      setRecords(allRecords);
      return allRecords;
    } catch (error: any) {
      console.error('Load all records failed:', error);
    }
  },[]);

  // 添加记录
  const handleAddRecord = useCallback(async (
    fields: Field[],
    loadRecordsFn: () => Promise<void>
  ) => {
    const title = prompt(locale.enterRecordTitle);
    if (!title || !title.trim()) {
      return;
    }
    
    try {
      const primaryFieldName = getPrimaryFieldName(fields);
      const recordFields: {[key: string]: any} = {
        [primaryFieldName]: title,
      };
      
      await Dingdocs.script.run('addRecord', recordFields);
      console.log(`✅ ${locale.addRecordSuccess}`);
      await loadRecordsFn();
    } catch (error: any) {
      alert(`${locale.operationFailed}: ${error.message}`);
    }
  }, [locale]);

  // 删除记录
  const handleDeleteRecord = useCallback(async (
    recordId: string,
    loadRecordsFn: () => Promise<void>
  ) => {
    if (!window.confirm(locale.confirmDelete)) {
      return;
    }
    
    try {
      await Dingdocs.script.run('deleteRecord', recordId);
      console.log(`✅ ${locale.deleteRecordSuccess}`);
      await loadRecordsFn();
    } catch (error: any) {
      alert(`${locale.operationFailed}: ${error.message}`);
    }
  }, [locale]);

  return {
    records, 
    setRecords,
    loadAllRecords,
    loadRecords,
    handleAddRecord,
    handleDeleteRecord
  };
};